import React, { Component } from 'react';
import { connect } from 'dva';
import { Form, Button, DatePicker, Row, Col, Select, Table, Input } from 'antd';
import moment from 'moment';

import Drawer from '../../components/drawer/Drawer';
import OrderInfo from './component/OrderInfo';

import './styles.less';


const FormItem = Form.Item;
const Option = Select.Option;
const formItemLayout = {
  labelCol: { span: 7 },
  wrapperCol: { span: 16 },
};

class MerchantOrder extends Component {
  state = {
    itemData: {},
  }
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'order/getBusniessLst',
    }).then(() => {
      this.handleSubmit(1);
    });
  }
  componentWillUnmount() {
    this.props.dispatch({
      type: 'order/clear',
    });
  }
  handleSubmit = (pageNo = 1) => {   // 查询列表
    const { form, dispatch } = this.props;
    form.validateFields((err, values) => {
      if (!err) {
        const reqData = {};
        reqData.pageNo = pageNo;
        Object.keys(values).forEach((item) => {
          if (values[item]) {
            reqData[item] = values[item];
          }
        });
        if (reqData.time) {
          reqData.ymd = `${moment(reqData.time).format('YYYYMMDD')}`;
          delete reqData.time;
        }
        dispatch({
          type: 'order/getMerchantOrderLst',
          payload: {
            ...reqData,
          },
        });
        this.pageNo = pageNo;
      }
    });
  }
  openDrawer = (item) => {   // 查看详情 打开抽屉
    this.props.dispatch({
      type: 'root/openDrawer',
    });
    this.setState({
      itemData: item,
    });
  }
  closeDrawer = () => {    // 关闭抽屉
    this.props.dispatch({
      type: 'root/closeDrawer',
    });
  }
  handleReset = () => {
    this.props.form.resetFields();
    this.handleSubmit(1);
  }
  render() {
    const { form, root, order } = this.props;
    const { merchantOrderLst = {}, busniessList = [] } = order;
    const { drawerStatus, busniessLst = {} } = root;
    const { getFieldDecorator } = form;
    const columns = [{
      title: '商户名称',
      fixed: 'left',
      className: 'merchant-name-cell',
      render: (val) => {
        return (<div>{val.merchantName}（{val.merchantNo}）</div>);
      },
    }, {
      title: '外部订单号',
      dataIndex: 'outOrderNo',
    }, {
      title: '交易时间',
      dataIndex: 'creatTime',
      render: (val) => {
        return val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : '';
      },
    }, {
      title: '流水号',
      dataIndex: 'orderNo',
      key: 'orderNo',
    }, {
      title: '用时（毫秒）',
      dataIndex: 'costTime',
      render: (val) => {
        return (val ? val / 1000000 : '');
      },
    }, {
      title: '申请数据',
      dataIndex: 'business',
      render: (val) => {
        return val && busniessLst[val] ? (busniessLst[val].name) : '';
      },
    }, {
      title: '查询单价（元/笔）',
      dataIndex: 'fee',
      key: 'fee',
    }, {
      title: '计费信息',
      dataIndex: 'feeFlag',
      render: (val) => {
        return (val == 'init' ? '未知' : val == 'free' ? '不计费' : val == 'payed' ? '计费' : '');
      },
    }, {
      title: '返回Code',
      dataIndex: 'code',
    }, {
      title: '返回信息',
      dataIndex: 'msg',
      width: '15%',
    }, {
      title: '结算状态',
      dataIndex: 'settleState',
      render: (val) => {
        return (val == 'ing' ? '待结算' : val == 'end' ?
          <div>
            <p>已生成</p>
            <p>结算单</p>
          </div> : '');
      },
    }, {
      title: '订单状态',
      dataIndex: 'state',
      render: (val) => {
        return (val == 'init' ? '请求中' : val == 'ret' ? '已完成' : val == 'setteled' ? '已生成完结算单' : '');
      },
    }, {
      title: '操作',
      fixed: 'right',
      className: 'operation-cell',
      render: (item) => {
        return (
          <a onClick={() => this.openDrawer(item)}>查看详情</a>
        );
      },
    }];
    return (
      <div className="g-pages merchant-order-pages">
        <Form
          className="g-form"
          hideRequiredMark={true}
          onSubmit={(e) => {
            e.preventDefault();
            this.handleSubmit();
          }}
        >
          <Row type="flex" justify="start">
            <Col span={8}>
              <FormItem {...formItemLayout} label="查询时间">
                { getFieldDecorator('time', {
                })(
                  <DatePicker
                    style={{width: '100%'}}
                    format="YYYY-MM-DD"
                    allowClear={false}
                    disabledDate={(current) => {
                      return current && current >= moment().endOf('day');
                    }}
                  />,
                )}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem {...formItemLayout} label="数据业务类型">
                { getFieldDecorator('business', {
                  rules: [{
                    message: '请选择数据业务类型',
                    whitespace: true,
                  }],
                })(
                  <Select placeholder="请选择数据业务类型">
                    {
                      busniessList.length ?
                      busniessList.map(item =>
                        <Option key={item.code} value={item.code}>{item.name}</Option>,
                      ) : null
                    }
                  </Select>,
                )}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem {...formItemLayout} label="订单号">
                { getFieldDecorator('outOrderNo', {
                  initialValue: '',
                  rules: [{
                    message: '请输入外部订单号',
                    whitespace: true,
                  }],
                })(
                  <Input placeholder="请输入外部订单号" maxLength="30" />,
                )}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem {...formItemLayout} label="查询耗时">
                { getFieldDecorator('costtime', {
                  initialValue: '',
                  rules: [{
                    message: '请输入查询耗时',
                    whitespace: true,
                  }],
                })(
                  <Input placeholder="查询结果为大于该值的记录(毫秒)" maxLength="30" />,
                )}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem {...formItemLayout} label="返回Code">
                { getFieldDecorator('code', {
                  initialValue: '',
                  rules: [{
                    message: '请输入返回Code',
                    whitespace: true,
                  }],
                })(
                  <Input placeholder="请输入返回Code" maxLength="15" />,
                )}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem {...formItemLayout} label="返回信息">
                { getFieldDecorator('msg', {
                  initialValue: '',
                  rules: [{
                    message: '请输入返回信息',
                    whitespace: true,
                  }],
                })(
                  <Input placeholder="请输入返回信息" maxLength="100" />,
                )}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem {...formItemLayout} label="关键字">
                { getFieldDecorator('key', {
                })(
                  <Input placeholder="请输入关键字" maxLength="30" />,
                )}
              </FormItem>
            </Col>
            <Col span={8} className="btn-bar">
              <Button type="primary" htmlType="submit">查询</Button>
              <Button className="ant-col-offset-1" onClick={() => this.handleReset()}>重置</Button>
            </Col>
          </Row>
        </Form>

        <div className="g-table-cell" style={{flex: 1, paddingTop: 0}}>
          <Table
            title={() => {
              return <div style={{fontSize: 14}}>总交易条数<span style={{color: '#4C9CDF', padding: '0 5px'}}>{merchantOrderLst.total || 0}</span>条</div>;
            }}
            columns={columns}
            dataSource={merchantOrderLst.list || []}
            scroll={{ x: 2000 }}
            pagination={{
              total: merchantOrderLst && merchantOrderLst.total ?
              merchantOrderLst.total : 1,
              onChange: (pageNum) => {
                this.handleSubmit(pageNum);
              },
            }}
          />
        </div>

        <Drawer open={drawerStatus} className="transaction-drawer">
          <OrderInfo
            closeDrawer={() => this.closeDrawer()}
            data={this.state.itemData}
          />
        </Drawer>
      </div>
    );
  }
}


export default connect((state) => {
  return {
    order: state.order,
    root: state.root,
  };
})(Form.create()(MerchantOrder));
